//
//  ViewController.swift
//  DEMO4
//
//  Created by J on 16/5/8.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    
    
    @IBAction func itemClick(sender: AnyObject) {
        var strM = String()

        //后去需要发送给服务器的数据
        self.customTextView.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.customTextView.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue:0)) { (objc, range:NSRange, _) in
         //如果字符串中间有图片表情 安么range就会传递多次

            if objc["NSAttachment"] != nil{
                let attachMent = objc["NSAttachment"] as! EmoticonNSTextAttachment
                //图片
                strM += attachMent.chs!
                
            }else{
                //文字
                strM += (self.customTextView.text as NSString).substringWithRange(range)
            }
            
            
        }
        print(strM)

    }

    @IBOutlet weak var customTextView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        customTextView.inputView = emojiController.view

    }
 
    //weak 相当月OC中weak 特点是对象释放会将变量设置为nil
    //unowned 相当于 unsafe_unretained 对象释放 不会将对象置为nil
    private lazy var emojiController : EmojiViewController = EmojiViewController {[unowned self] (emoticon) in
        //选中表情回调
        print(emoticon.chs)

        //1.判断当前点击的是否是eomoji
        if emoticon.code != nil {
            let range = self.customTextView.selectedTextRange
            self.customTextView.replaceRange(range!, withText: emoticon.emojiStr!)//textRange
        }
        
        //2.判断是否是表情图片
        if emoticon.png != nil{
            //1.创建图片属性字符串
            
            let attach = EmoticonNSTextAttachment()//创建附件图片
            attach.chs = emoticon.chs//设置图片的名称
            attach.image =  UIImage(contentsOfFile: emoticon.imagePath!)
            attach.bounds = CGRect(x: 0, y: -4, width: 17, height: 17)//设置附件大小
            //2.根据附件创建属性字符串
            let imageText = NSAttributedString(attachment: attach)//创建属性字符串
            
            //3.拿到当前所有内容
            let strM = NSMutableAttributedString(attributedString: self.customTextView.attributedText)
            //4.插入表情到当前光标坐在位置
            let selectRange = self.customTextView.selectedRange
            strM.replaceCharactersInRange(selectRange, withAttributedString: imageText)
            
            strM.addAttributes([NSFontAttributeName : UIFont.systemFontOfSize(17)], range: selectRange)//设置选中范围内属性字符串字体大小
            //5.将替换后的字符串 赋值给UITextView
            self.customTextView.attributedText = strM
            
            //恢复光标所在位置
            //1.制定光标位置  2.选中长度
            self.customTextView.selectedRange = NSMakeRange(selectRange.location+1, selectRange.length)

        }
        
    }

    deinit{


//        print("deinit")
    }

}

